package com.vb.ecm.web.custom.importcontent;

import com.documentum.fc.client.IDfCollection;

import com.documentum.fc.client.DfClient;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfGroup;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.client.IDfSysObject;
import com.documentum.fc.client.IDfUser;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.DfLoginInfo;
import com.documentum.fc.common.IDfLoginInfo;
//import com.documentum.ucf.common.configuration.impl.ConfigurationService;
import com.documentum.web.common.*;
import com.documentum.web.contentxfer.*;
import com.documentum.web.contentxfer.impl.ImportService;
import com.documentum.web.form.*;
import com.documentum.web.form.control.*;
import com.documentum.web.form.control.databound.DataDropDownList;
import com.documentum.web.formext.common.BackDetector;
import com.documentum.web.formext.component.Component;
import com.documentum.web.formext.config.ConfigService;
import com.documentum.web.formext.config.Context;
import com.documentum.web.formext.config.IConfigElement;
import com.documentum.web.formext.config.IConfigLookup;
import com.documentum.web.formext.control.docbase.*;
import com.documentum.web.formext.control.validator.FolderSelectionValidator;
import com.documentum.web.formext.session.SessionManagerHttpBinding;
import com.documentum.webcomponent.common.WebComponentErrorService;
import com.documentum.webcomponent.environment.preferences.searchsources.SearchSourceService;
import com.documentum.webcomponent.library.contenttransfer.ContentTransferServiceContainer;
import com.documentum.webcomponent.library.contenttransfer.importcontent.ImportContent;
import com.documentum.webcomponent.library.messages.MessageService;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.set.ListOrderedSet;
import org.apache.log4j.Logger;

// Referenced classes of package com.documentum.webcomponent.library.contenttransfer.importcontent:
//            ImportContent

/**
 * @author naresh bundle
 * 
 */

public abstract class CustomImportContentContainer extends ContentTransferServiceContainer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	static String T_ID;

	private static final Logger LOGGER = Logger.getLogger(CustomImportContentContainer.class);

	String objectId = null;

	IDfSysObject losObject = null;

	private static class DirsFirstComparator implements Comparator {

		@Override
		public int compare(Object o1, Object o2) {
			ImportFile f1 = (ImportFile) o1;
			ImportFile f2 = (ImportFile) o2;
			if (f1.isDirectory()) {
				return f2.isDirectory() ? 0 : -1;
			} else {
				return f2.isDirectory() ? 1 : 0;
			}
		}

		private DirsFirstComparator() {
		}

	}

	public static class ImportFile {
		private String fileName;
		private String parentPath;
		private String filePath;
		private String localFilePath;
		private boolean directory;
		private String format;
		// private String unit;
		private String strTransactionId = null;
		Label lshowValidation = null;

		private ArgumentList attributes;
		private IDfSysObject transObject;

		public IDfSysObject getTransObject() {
			return transObject;
		}

		private String r_object_id, owner_name, doc_upload_status, doc_sub_type, branch_number, cust_id_number, cust_type, cust_name, collateral_id, cust_cif_number, cust_id_type,
				facility_number, upload_by, car_year_created;

		public String getUpload_by() {
			return upload_by;
		}

		public void setUpload_by(String upload_by) {
			this.upload_by = upload_by;
		}

		public String getCar_year_created() {
			return car_year_created;
		}

		public void setCar_year_created(String car_year_created) {
			this.car_year_created = car_year_created;
		}

		public void setTransObject(IDfSysObject transObject) {
			this.transObject = transObject;
		}

		public String getR_object_id() {
			return r_object_id;
		}

		public void setR_object_id(String r_object_id) {
			this.r_object_id = r_object_id;
		}

		/*
		 * public String getObject_name() { return object_name; }
		 * 
		 * public void setObject_name(String object_name) { this.object_name =
		 * object_name; }
		 */
		public String getOwner_name() {
			return owner_name;
		}

		public void setOwner_name(String owner_name) {
			this.owner_name = owner_name;
		}

		public String getDoc_upload_status() {
			return doc_upload_status;
		}

		public void setDoc_upload_status(String doc_upload_status) {
			this.doc_upload_status = doc_upload_status;
		}

		public String getDoc_sub_type() {
			return doc_sub_type;
		}

		public void setDoc_sub_type(String doc_sub_type) {
			this.doc_sub_type = doc_sub_type;
		}

		public String getBranch_number() {
			return branch_number;
		}

		public void setBranch_number(String branch_number) {
			this.branch_number = branch_number;
		}

		/*
		 * public String getCust_email() { return cust_email; }
		 * 
		 * public void setCust_email(String cust_email) { this.cust_email =
		 * cust_email; }
		 */

		public String getCust_id_number() {
			return cust_id_number;
		}

		public void setCust_id_number(String cust_id_number) {
			this.cust_id_number = cust_id_number;
		}

		public String getCust_type() {
			return cust_type;
		}

		public void setCust_type(String cust_type) {
			this.cust_type = cust_type;
		}

		public String getCust_name() {
			return cust_name;
		}

		public void setCust_name(String cust_name) {
			this.cust_name = cust_name;
		}

		/*
		 * public String getRm_name() { return rm_name; }
		 * 
		 * public void setRm_name(String rm_name) { this.rm_name = rm_name; }
		 */
		public String getCollateral_id() {
			return collateral_id;
		}

		public void setCollateral_id(String collateral_id) {
			this.collateral_id = collateral_id;
		}

		/*
		 * public String getTransaction_user() { return transaction_user; }
		 * 
		 * public void setTransaction_user(String transaction_user) {
		 * this.transaction_user = transaction_user; }
		 */

		/*
		 * public String getCust_phone() { return cust_phone; }
		 * 
		 * public void setCust_phone(String cust_phone) { this.cust_phone =
		 * cust_phone; }
		 */

		public String getCust_cif_number() {
			return cust_cif_number;
		}

		public void setCust_cif_number(String cust_cif_number) {
			this.cust_cif_number = cust_cif_number;
		}

		/*
		 * public String getRm_id() { return rm_id; }
		 * 
		 * public void setRm_id(String rm_id) { this.rm_id = rm_id; }
		 */

		public String getCust_id_type() {
			return cust_id_type;
		}

		public void setCust_id_type(String cust_id_type) {
			this.cust_id_type = cust_id_type;
		}

		/*
		 * public String getCar_number() { return car_number; }
		 * 
		 * public void setCar_number(String car_number) { this.car_number =
		 * car_number; }
		 */

		public String getFacility_number() {
			return facility_number;
		}

		public void setFacility_number(String facility_number) {
			this.facility_number = facility_number;
		}

		public IDfSysObject getFolderPathObject() {
			return folderPathObject;
		}

		public void setFolderPathObject(IDfSysObject folderPathObject) {
			this.folderPathObject = folderPathObject;
		}

		public String getR_folder_path() {
			return r_folder_path;
		}

		public void setR_folder_path(String r_folder_path) {
			this.r_folder_path = r_folder_path;
		}

		public void setFileName(String fileName) {
			this.fileName = fileName;
		}

		public void setParentPath(String parentPath) {
			this.parentPath = parentPath;
		}

		public void setFilePath(String filePath) {
			this.filePath = filePath;
		}

		public void setLocalFilePath(String localFilePath) {
			this.localFilePath = localFilePath;
		}

		public void setDirectory(boolean directory) {
			this.directory = directory;
		}

		public void setFormat(String format) {
			this.format = format;
		}

		public void setStrTransactionId(String strTransactionId) {
			this.strTransactionId = strTransactionId;
		}

		public void setAttributes(ArgumentList attributes) {
			this.attributes = attributes;
		}

		private IDfSysObject folderPathObject;
		private String r_folder_path;

		private static String parseFileName(String filePath) {

			String name = filePath;

			LOGGER.debug("filePath00001......." + name);
			if (filePath != null && filePath.length() > 0) {
				int sepIndex = filePath.charAt(0) != '/' ? filePath.lastIndexOf('\\') : filePath.lastIndexOf('/');
				if (sepIndex != -1) {
					name = filePath.substring(sepIndex + 1, filePath.length());
				}
			}
			LOGGER.debug("file Name===" + name);

			return name;
		}

		public String getFileName() {
			return fileName;
		}

		public String getStrTransactionId() {
			return strTransactionId;
		}

		public void setStrUnitName(String strTransactionId) {
			this.strTransactionId = strTransactionId;
		}

		public String getFilePath() {
			LOGGER.debug("2===" + filePath);
			return filePath;
		}

		public String getLocalFilePath() {
			LOGGER.debug("getLocalFilePath........." + filePath);
			return localFilePath;
		}

		public String getParentPath() {
			return parentPath;
		}

		public boolean isDirectory() {
			return directory;
		}

		public String getFormat() {
			return format;
		}

		public ArgumentList getAttributes() {
			// LOGGER.debug("attributes==="+attributes.get("0"));
			return attributes;
		}

		public ImportFile(String name, String filePath, String localFilePath, String parentFilePath, boolean dir, ArgumentList attributes, String format) {
			directory = false;
			this.filePath = filePath;
			LOGGER.debug("filePath000003::::::::" + filePath);
			fileName = name == null || name.length() <= 0 ? parseFileName(filePath) : name;
			this.localFilePath = localFilePath;
			parentPath = parentFilePath;
			directory = dir;
			this.attributes = attributes;
			this.format = format;

		}

		public ImportFile(String name, String filePath, String localFilePath, String parentFilePath, boolean dir) {
			this(name, filePath, localFilePath, parentFilePath, dir, null, null);
		}

		public ImportFile(String filePath, String localFilePath) {
			this(null, filePath, localFilePath, null, false);

		}

		public ImportFile(String strTransactionId, IDfSession idfSession, String s) throws Exception{
			this.strTransactionId = strTransactionId;
			LOGGER.debug("Enter into ImportFile() of CustomImportContentContainer");
			LOGGER.debug("Importing Documents for this Transaction ID:" + strTransactionId);

				if (strTransactionId != null) {
					transObject = (IDfSysObject) idfSession.getObjectByQualification("vb_los_docs where r_object_id='" + strTransactionId + "'");
					r_object_id = transObject.getString("r_object_id");
					// object_name=transObject.getString("object_name");
					doc_upload_status = transObject.getString("doc_upload_status");
					doc_sub_type = transObject.getString("doc_sub_type");
					branch_number = transObject.getString("branch_number");
					// cust_email=transObject.getString("cust_email");
					cust_id_number = transObject.getString("cust_id_number");
					cust_type = transObject.getString("cust_type");
					cust_name = transObject.getString("cust_name");
					// rm_name=transObject.getString("rm_name");
					collateral_id = transObject.getString("collateral_number");
					// transaction_user=transObject.getString("transaction_user");
					// cust_phone=transObject.getString("cust_phone");
					cust_cif_number = transObject.getString("cust_cif_number");
					// rm_id=transObject.getString("rm_id");
					cust_id_type = transObject.getString("cust_id_type");
					// car_number=transObject.getString("car_number");
					facility_number = transObject.getString("facility_number");
					upload_by = transObject.getString("upload_by");
					car_year_created = transObject.getString("car_year_created");

					folderPathObject = (IDfSysObject) idfSession.getObjectByQualification("dm_folder where r_folder_path!=' ' and"
							+ " r_object_id in(select distinct(i_folder_id) from vb_los_docs where r_object_id='" + strTransactionId + "') ENABLE(ROW_BASED)");

					r_folder_path = folderPathObject.getString("r_folder_path");
				}			
			LOGGER.debug("Exit from  ImportFile() of CustomImportContentContainer");
			// TODO Auto-generated constructor stub
		}

	}

	public static final String NEW_OBJECT_IDS = "newObjectIds";
	protected static final String EVENT_ONCHANGEOBJECTTYPE = "onchangeobjecttype";
	private static final String HANDLER_ONCHANGEOBJECTTYPE = "onChangeObjectType";
	private Set m_setFiles;
	private String m_folderId;
	private String m_targetDocbaseName;
	private int m_compStartedAutoCommit;
	private String m_pageStartedOnOk;
	private boolean m_fileFolderMix;
	private static final Comparator DIRS_FIRST = new DirsFirstComparator();

	// controls declarations
	// String processId;
	private Label checkLabel;
	private Label successLabel;
	Label lshowLabel = null;

	private DataDropDownList dddlTransactionId;

	private String sdddlTransactionId;

	private String object_name;

	private String owner_name;

	private String doc_upload_status;

	private String doc_sub_type;

	private String branch_number;

	// private String cust_email;

	private String cust_id_number;

	private String cust_type;

	private String cust_name;

	private String rm_name;

	private String rm_id;

	private String collateral_id;

	private String transaction_user;

	private String cust_phone;

	private String cust_cif_number;

	private String cust_id_type;

	private String car_number;

	private String facility_number;

	private String transObject;

	private String r_folder_path;

	private IDfSysObject transactionObject;

	private String upload_by;
	private String car_year_created;
	private static IDfSession idfSession;

	public CustomImportContentContainer() {
		m_setFiles = new HashSet();
		m_compStartedAutoCommit = -1;
		m_fileFolderMix = false;
	}

	@Override
	public void onInit(ArgumentList args) {

		super.onInit(args);
		LOGGER.debug("Enter into onInit() of CustomImportContentContainer");
		LOGGER.debug("Transaction ID received from this component:" + args.get("trans_id"));
		checkLabel = (Label) getControl("check_label", Label.class);
		successLabel = (Label) getControl("message_label", Label.class);
		StringBuffer buf = new StringBuffer(256);
		// LOGGER.debug("form.getURL"+getForm().getUrl());
		// buf.append("http://localhost:8081/webtop/action/import_los?objectId=0c01e24080000107");
		// String url = makeUrl(getPageContext().getRequest(), buf.toString());
		// LOGGER.debug("path==="+getPageContext().getRequest());
		HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest();
		String fullUrl = request.getRequestURL().toString();
		LOGGER.debug("URL==========" + fullUrl);
		getPreviousButtonControl(true).setEnabled(false);
		String filePathArray[] = args.getValues("filePath");
		LOGGER.debug("filePath:");
		String parentPathArray[] = args.getValues("parentPath");
		String isDirectoryArray[] = args.getValues("isDirectory");
		// rsb = ResourceBundle.getBundle("losConfig");
		// processId = "4b00303980000995";
		if (filePathArray != null) {
			if (parentPathArray == null || isDirectoryArray == null) {
				throw new IllegalArgumentException("filePath argument can not be specified without specifying parentPath and isDirec" + "tory arguments!");
			}
			if (filePathArray.length != parentPathArray.length || filePathArray.length != isDirectoryArray.length) {
				throw new IllegalArgumentException("The number of values specified for filePath, parentPath and isDirectory argument" + "s must match!");
			}
			int itemsToImport = filePathArray.length;
			ArrayList filesList = new ArrayList(itemsToImport);
			for (int itemIndex = 0; itemIndex < itemsToImport; itemIndex++) {
				String filePath = filePathArray[itemIndex];
				LOGGER.debug("filePath:" + filePath);

				String parentPath = parentPathArray[itemIndex];
				if (parentPath != null && parentPath.length() == 0) {
					parentPath = null;
				}
				boolean isDirectory = Boolean.valueOf(isDirectoryArray[itemIndex]).booleanValue();
				String initialFormat = args.get("format");
				if (isDirectory) {
					initialFormat = "";
				}
				ImportFile importFile = new ImportFile(null, filePath, null, parentPath, isDirectory, null, initialFormat);
				filesList.add(importFile);
			}

			setFilesToImport(filesList);
		}
		SearchSourceService searchSourceService = SearchSourceService.getInstance();
		MultiDocbaseTree repositoriesSelTree = (MultiDocbaseTree) getControl("folderlocator", com.documentum.web.formext.control.docbase.MultiDocbaseTree.class);
		if (repositoriesSelTree != null && searchSourceService != null) {
			repositoriesSelTree.setDocbaseList(searchSourceService.getAvailableSearchSources());
		}
		objectId = args.get("objectId");
		if (objectId != null && objectId.length() > 0) {
			setFolderId(objectId);
		}
		if (getFolderId() == null || getFolderId().length() == 0) {
			setComponentPage("folderselection");
		} else if (getFilesToImport() == null || getFilesToImport().size() == 0) {
			setComponentPage("fileselection");
		} else {
			initContainedComponents();
			setComponentPage("containerstart");
		}
		LOGGER.debug("Exit from onInit() of CustomImportContentContainer");
	}

	@Override
	public void onOk(Control button, ArgumentList args) {

		LOGGER.debug("onOk==" + args.get("0") + "," + args.get("1"));
		String previousCurrentDocbase;

		m_pageStartedOnOk = getComponentPage();		
		LOGGER.debug("in auto commit==" + inAutoCommit());
		if (!inAutoCommit()) {
			String strCurPage = getComponentPage();
			if (!strCurPage.equals("containerstart")) {
				if (onNextPage()) {
					strCurPage = getComponentPage();
					if (!strCurPage.equals("containerstart")) {
						return;
					}
				} else {
					return;
				}
			}
		}
		validate();

		if (getIsValid() && canCommitChanges() && canCommitComponentsChanges() && onCommitChanges()) {
			ImportContent importComponent = (ImportContent) getContainedComponent();
			boolean m_blnContinueEdit = importComponent.isContinueEdit();
			previousCurrentDocbase = null;
			if (getTargetDocbaseName() != null) {
				previousCurrentDocbase = SessionManagerHttpBinding.getCurrentDocbase();
				SessionManagerHttpBinding.setCurrentDocbase(getTargetDocbaseName());
			}
			try {
				invokeService();
			} catch (ContentTransferException e) {
				throw new WrapperRuntimeException(e);
			} finally {
				if (previousCurrentDocbase == null)
					SessionManagerHttpBinding.setCurrentDocbase(previousCurrentDocbase);

			}
			if (previousCurrentDocbase != null) {
				SessionManagerHttpBinding.setCurrentDocbase(previousCurrentDocbase);
			}
		}

	}

	private boolean canCommitComponentsChanges() {
		boolean isValid = true;
		List components = getContainedComponents();
		for (int i = 0; i < components.size(); i++) {
			Component component = (Component) components.get(i);
			isValid = component.canCommitChanges();
			if (!isValid) {
				if (inAutoCommit()) {
					stopAutoCommit();
				}
				setCurrentComponent(i);
				return isValid;
			}
		}

		return isValid;
	}

	@Override
	public String[] getEventNames() {
		return Util.concatarray(super.getEventNames(), new String[] { "onchangeobjecttype" });
	}

	@Override
	public String getEventHandlerMethod(String strEvent) {
		String strMethod = null;
		if (strEvent.equals("onchangeobjecttype")) {
			strMethod = "onChangeObjectType";
		} else {
			strMethod = super.getEventHandlerMethod(strEvent);
		}
		return strMethod;
	}

	@Override
	public Control getEventHandler(String strEvent) {
		Control handler = null;
		if (strEvent.equals("onchangeobjecttype")) {
			handler = this;
		} else {
			handler = super.getEventHandler(strEvent);
		}
		return handler;
	}

	public void onChangeObjectType(Control control, ArgumentList arg) {
		String strType = arg.get("type");
		String strObjectName = arg.get("objectName");
		String strFormat = arg.get("format");
		ArgumentList containedArg = getContainedComponentArgs();
		containedArg.replace("docbaseType", strType);
		containedArg.replace("objectName", strObjectName);
		containedArg.replace("format", strFormat);
		Component comp = getContainedComponent();
		remove(comp);
		getContainedComponent();
	}

	@Override
	public void onControlInitialized(Form form, Control control) {
		String strControlName = control.getName();
		String strInitialValue = null;
		if (!"formatList".equals(strControlName) && !"attribute_object_name".equals(strControlName)) {
			if ("objectTypeList".equals(strControlName) && (control instanceof DataDropDownList)) {
				strInitialValue = ((DataDropDownList) control).getValue();
			} else if ("docbaseObj".equals(strControlName) && (control instanceof DocbaseObject)) {
				onDocbaseObjectInitialized((DocbaseObject) control);
			}
			super.onControlInitialized(form, control);
		}
		if ("objectTypeList".equals(strControlName) && (control instanceof DataDropDownList)) {
			String strValue = ((DataDropDownList) control).getValue();
			if (strValue != null && !strValue.equals(strInitialValue)) {
				ArgumentList eventArgs = new ArgumentList();
				eventArgs.add("initType", strInitialValue);
				eventArgs.add("newType", strValue);
				Component comp = getContainedComponent();
				comp.fireEvent("onsynctype", eventArgs);
			}
		}
	}

	private void onDocbaseObjectInitialized(DocbaseObject docbaseObj) {
		int index = getCurrentComponent();
		if (index > 0) {
			ArgumentList containedArg = getContainedComponentArgs();
			String docbaseType = containedArg.get("docbaseType");
			if (docbaseType == null || docbaseType.length() == 0) {
				docbaseType = getPrevType();
			}
			if (docbaseType != null && docbaseType.length() > 0) {
				docbaseObj.setType(docbaseType);
			}
		}
	}

	private String getPrevType() {
		boolean isCurrentDir = isCurrenFileToImportDirectory();
		int current = getCurrentComponent();
		String docbaseType = null;
		for (int i = current - 1; i >= 0; i--) {
			setCurrentComponent(i);
			if (isCurrentDir != isCurrenFileToImportDirectory() || !(getContainedComponent() instanceof CustomImportComponent)) {
				continue;
			}
			CustomImportComponent prevComponent = (CustomImportComponent) getContainedComponent();
			DocbaseObject prevDocbaseObj = prevComponent.getDocbaseObjectControl(false);
			if (prevDocbaseObj == null) {
				continue;
			}
			docbaseType = prevDocbaseObj.getType();
			break;
		}

		setCurrentComponent(current);
		return docbaseType;
	}

	@Override
	public boolean onNextPage() {
		boolean bRet = false;
		IDfCollection col = null;
		MessageService.clear(this);
		try {
			LOGGER.debug("Enter into onNextPage() of CustomImportContentContainer");
			// dddlTransactionId =
			// (DataDropDownList)getControl("transList",DataDropDownList.class);
			// sdddlTransactionId = dddlTransactionId.getValue();

			ArgumentList compArgs = getContainedComponentArgs();
			ArgumentList args = new ArgumentList(compArgs);
			sdddlTransactionId = args.get("trans_id");
			LOGGER.debug("component args trans_id==" + compArgs.get("trans_id"));
			LOGGER.debug("Transaction Id:" + sdddlTransactionId);
			if (sdddlTransactionId.length() > 0) {

				ImportFile i = new ImportFile(sdddlTransactionId, getDfSession(), null);

				if (i.getStrTransactionId() != null) {
					args.add("trans_id", i.getStrTransactionId());
					LOGGER.debug("transaction ID:=" + args.get("trans_id"));
					compArgs.add("trans_id", i.getStrTransactionId());

				}

				/*
				 * if (i.getObject_name() != null) { args.add("object_name",
				 * i.getObject_name());
				 * LOGGER.debug("object_name in args$$$$$$$$$$$=" +
				 * args.get("object_name"));
				 * 
				 * object_name=args.get("object_name");
				 * compArgs.add("object_name", i.getObject_name());
				 * 
				 * }
				 */
				/*
				 * if (i.getOwner_name() != null) { args.add("owner_name",
				 * i.getOwner_name());
				 * LOGGER.debug("getOwner_name in args$$$$$$$$$$$=" +
				 * args.get("owner_name")); owner_name = args.get("owner_name");
				 * compArgs.add("owner_name", i.getOwner_name());
				 * 
				 * }
				 */
				if (i.getDoc_upload_status() != null) {
					args.add("doc_upload_status", i.getDoc_upload_status());
					LOGGER.debug("doc_upload_status:" + args.get("doc_upload_status"));
					doc_upload_status = args.get("doc_upload_status");
					compArgs.add("doc_upload_status", i.getDoc_upload_status());

				}

				if (i.getDoc_sub_type() != null) {
					args.add("doc_sub_type", i.getDoc_sub_type());
					LOGGER.debug("doc_sub_type:" + args.get("doc_sub_type"));
					doc_sub_type = args.get("doc_sub_type");
					compArgs.add("doc_sub_type", i.getDoc_sub_type());

				}

				if (i.getBranch_number() != null) {
					args.add("branch_number", i.getBranch_number());
					LOGGER.debug("branch_number:" + args.get("branch_number"));

					branch_number = args.get("branch_number");
					compArgs.add("branch_number", i.getBranch_number());

				}
				if (i.getUpload_by() != null) {
					args.add("upload_by", i.getUpload_by());
					LOGGER.debug("upload_by:" + args.get("upload_by"));

					upload_by = args.get("upload_by");
					compArgs.add("upload_by", i.getUpload_by());

				}

				/*
				 * if (i.getCust_email() != null) { args.add("cust_email",
				 * i.getCust_email());
				 * LOGGER.debug("cust_email in args$$$$$$$$$$$=" +
				 * args.get("cust_email")); cust_email=args.get("cust_email");
				 * compArgs.add("cust_email", i.getCust_email());
				 * 
				 * 
				 * }
				 */

				if (i.getCust_id_number() != null) {
					args.add("cust_id_number", i.getCust_id_number());
					LOGGER.debug("cust_id_number:" + args.get("cust_id_number"));
					cust_id_number = args.get("cust_id_number");
					compArgs.add("cust_id_number", i.getCust_id_number());

				}

				if (i.getCust_type() != null) {
					args.add("cust_type", i.getCust_type());
					LOGGER.debug("cust_type:" + args.get("cust_type"));
					cust_type = args.get("cust_type");
					compArgs.add("cust_type", i.getCust_type());

				}

				if (i.getCust_name() != null) {
					args.add("cust_name", i.getCust_name());
					LOGGER.debug("cust_name:" + args.get("cust_name"));
					cust_name = args.get("cust_name");
					compArgs.add("cust_name", i.getCust_name());

				}

				if (i.getCollateral_id() != null) {
					args.add("collateral_id", i.getCollateral_id());
					LOGGER.debug("collateral_id:" + args.get("collateral_id"));
					collateral_id = args.get("collateral_id");
					compArgs.add("collateral_id", i.getCollateral_id());

				}

				if (i.getCust_cif_number() != null) {
					args.add("cust_cif_number", i.getCust_cif_number());
					LOGGER.debug("cust_cif_number:" + args.get("cust_cif_number"));
					cust_cif_number = args.get("cust_cif_number");
					compArgs.add("cust_cif_number", i.getCust_cif_number());

				}

				if (i.getCust_id_type() != null) {
					args.add("cust_id_type", i.getCust_id_type());
					LOGGER.debug("cust_id_type:" + args.get("cust_id_type"));
					cust_id_type = args.get("cust_id_type");
					compArgs.add("cust_id_type", i.getCust_id_type());

				}

				if (i.getCar_year_created() != null) {
					args.add("car_year_created", i.getCar_year_created());
					LOGGER.debug("car year created:" + args.get("car_year_created"));
					car_year_created = args.get("car_year_created");
					compArgs.add("car_year_created", i.getCar_year_created());

				}

				if (i.getFacility_number() != null) {
					args.add("facility_number", i.getFacility_number());
					LOGGER.debug("facility_number:" + args.get("facility_number"));
					facility_number = args.get("facility_number");
					compArgs.add("facility_number", i.getFacility_number());

				}

				if (i.getTransObject() != null) {
					args.add("transObject", i.getTransObject().toString());
					// LOGGER.debug("transObject in args$$$$$$$$$$$=" +
					// args.get("transObject"));
					transObject = args.get("transObject");
					compArgs.add("transObject", i.getTransObject().toString());

				}

				if (i.getR_folder_path() != null) {
					args.add("r_folder_path", i.getR_folder_path());
					LOGGER.debug("r_folder_path:" + args.get("r_folder_path"));
					r_folder_path = args.get("r_folder_path");
					compArgs.add("r_folder_path", i.getR_folder_path());

				}

				/*
				 * Button b1 = (Button) getControl("ok", Button.class);
				 * b1.setVisible(false); b1.setEnabled(false);
				 */
				String strCurPage = getComponentPage();

				if (strCurPage.equals("fileselection")) {
					bRet = processOnNextPageFromFileSelection();
				} else if (strCurPage.equals("folderselection")) {
					bRet = processOnNextPageFromFolderSelection();
				} else {
					bRet = processOnNextPageFromImport();
				}

			} else {
				lshowLabel.setLabel("All fields are mandatory.");
			}

		} catch (Exception e) {
			e.printStackTrace();
			setComponentPage("error");
		} finally {
			try {
				// col.close();
			} catch (NumberFormatException ex) {
				ex.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return bRet;

	}

	@Override
	public boolean onPrevPage() {
		Component component = getContainedComponent();
		component.validate();
		return super.onPrevPage();
	}

	protected boolean processOnNextPageFromImport() {
		if (isFilesToImportSorted() && inAutoCommit() && m_pageStartedOnOk != null && m_pageStartedOnOk.equals("containerstart")
				&& getCurrentComponent() != m_compStartedAutoCommit && isCurrenFileToImportDirectory() != isPreviousFileToImportDirectory()) {
			stopAutoCommit();
			LOGGER.debug("processOnNextPageFromImport");
			// new CustomImportComponent().setComponentPage("success");
			return false;
		}
		String strType = "";
		if (inAutoCommit()) {
			ArgumentList arg = getContainedComponentArgs();
			strType = arg.get("type");
			LOGGER.debug("strType:" + strType);
		}
		boolean bRet = super.onNextPage();
		if (bRet && inAutoCommit()) {
			ArgumentList arg = new ArgumentList(getContainedComponentArgs());
			arg.replace("type", strType);
			LOGGER.debug("args:" + arg);
			setContainedComponentArgs(arg);
		}
		return bRet;
	}

	@Override
	protected void startAutoCommit() {
		m_compStartedAutoCommit = getCurrentComponent();
		super.startAutoCommit();
	}

	protected boolean processOnNextPageFromFileSelection() {
		LOGGER.debug("processOnNextPageFromFileSelection()");
		Collection files = getUploadedFilesFromRequest();
		if (files == null || files.size() == 0) {
			setReturnError("MSG_NO_FILES_SELECTED", null, null);
			ErrorMessageService.getService().setNonFatalError(this, "MSG_NO_FILES_SELECTED", null);
			return false;
		}

		Integer maxCount;
		if ((maxCount = lookupInteger("max-import-file-count")) != null && files.size() > maxCount.intValue()) {
			Object params[] = { new Integer(files.size()), maxCount };
			setReturnError("MSG_MAX_IMPORT_FILE_COUNT_EXCEEDED", params, null);
			ErrorMessageService.getService().setNonFatalError(this, "MSG_MAX_IMPORT_FILE_COUNT_EXCEEDED", params, null);
			return false;
		}
		ImportFile duplicateFolder;
		if ((duplicateFolder = findDuplicateFolder(files)) != null) {
			Object params[] = { duplicateFolder.getFileName() };
			setReturnError("MSG_DUPLICATE_FOLDERS_SELECTED", params, null);
			ErrorMessageService.getService().setNonFatalError(this, "MSG_DUPLICATE_FOLDERS_SELECTED", params, null);
			return false;
		}
		setFilesToImport(files);
		if (getFolderId() == null || getFolderId().length() == 0) {
			setComponentPage("folderselection");
		} else {
			initContainedComponents();
			setComponentPage("containerstart");
		}
		return true;
	}

	@Override
	public void onRender() {
		super.onRender();

		if (getComponentPage().equals("containerstart")) {
			updateFolderFileIndicator();
		}
	}

	protected void updateFolderFileIndicator() {
		Panel panel = getFolderFileIndicatorPanel(true);
		panel.setVisible(m_fileFolderMix);
		if (m_fileFolderMix) {
			Tabbar tabbar = getFolderFileIndicatorTabbar(false);
			if (tabbar != null) {
				Tab toBeSelected = isCurrenFileToImportDirectory() ? getFolderIndicatorTab(true) : getFileIndicatorTab(true);
				tabbar.setValue(toBeSelected.getName());
				Tab selected = tabbar.getSelectedTab();
				selected.setEnabled(true);
				Iterator iter = tabbar.getTabs();
				do {
					if (!iter.hasNext()) {
						break;
					}
					Tab tab = (Tab) iter.next();
					if (tab != selected) {
						tab.setEnabled(false);
					}
				} while (true);
			}
		}
	}

	private ImportFile findDuplicateFolder(Collection files) {
		Map map = new HashMap();
		for (Iterator iter = files.iterator(); iter.hasNext();) {
			ImportFile file = (ImportFile) iter.next();
			if (file.isDirectory()) {
				ArrayList key = new ArrayList(2);
				key.add(file.getFileName());
				key.add(file.getParentPath());
				ImportFile duplicate;
				if ((duplicate = (ImportFile) map.put(key, file)) != null) {
					return duplicate;
				}
			}
		}

		return null;
	}

	protected abstract Collection getUploadedFilesFromRequest();

	protected boolean processOnNextPageFromFolderSelection() {
		FolderSelectionValidator folderValidator = getFolderValidatorControl(true);
		folderValidator.validate();
		if (!folderValidator.getIsValid()) {
			return false;
		}
		MultiDocbaseTree repositoriesSelTree = getFolderLocatorControl(true);
		if (repositoriesSelTree.getSelectedNode() == null) {
			return false;
		}
		DocbaseFolderTreeNode selectedNode = (DocbaseFolderTreeNode) repositoriesSelTree.getSelectedNode();
		String folderId = selectedNode.getId();
		setFolderId(folderId);
		String docbaseName = selectedNode.getDocbaseName();
		setTargetDocbaseName(docbaseName);
		ArgumentList arg = getContainedComponentArgs();
		// LOGGER.debug("args=="+arg.get("0")+"args1=="+arg.get("1"));
		arg.replace("objectId", folderId);
		if (getFilesToImport() == null || getFilesToImport().size() == 0) {
			setComponentPage("fileselection");
		} else {
			initContainedComponents();
			setComponentPage("containerstart");
		}
		return true;
	}

	@Override
	protected void initContainedComponents() {
		LOGGER.debug("initContainedComponents()");
		Collection filesToImport = getFilesToImport();
		ArgumentList containedComponentsArgs[] = new ArgumentList[filesToImport.size()];
		ArgumentList compArgs = getContainedComponentArgs();
		int i = 0;
		for (Iterator iter = filesToImport.iterator(); iter.hasNext();) {
			ArgumentList args = new ArgumentList(compArgs);
			Object o = iter.next();
			if (o instanceof ImportFile) {
				ImportFile ifile = (ImportFile) o;
				if (ifile.getFilePath() != null) {
					args.add("filenameWithPath", ifile.getFilePath());
				}
				if (ifile.getLocalFilePath() != null) {
					args.add("localFilePath", ifile.getLocalFilePath());
				}
				if (ifile.getParentPath() != null) {
					args.add("parentPath", ifile.getParentPath());
				}
				args.add("isDirectory", String.valueOf(ifile.isDirectory()));
				if (ifile.getAttributes() != null && !ifile.getAttributes().isEmpty()) {
					args.add("defaultAttributesValues", ArgumentList.encode(ifile.getAttributes()));
				}
				if (ifile.getFormat() != null) {
					args.add("format", ifile.getFormat());
				}
			} else {
				args.add("filenameWithPath", o.toString());
			}
			containedComponentsArgs[i] = args;
			// LOGGER.debug(" containedComponentsArgs[i]" +
			// containedComponentsArgs[i]);
			i++;
		}

		setContainedComponentsArgs(containedComponentsArgs);
		super.initContainedComponents();
		setCurrentComponent(0);

	}

	@Override
	protected void handleOnReturnFromProgressSuccess(Form form, Map map, JobAdapter job) {

		String portName = null;
		String packageName = null;
		String packageType = null;
		IDfCollection col = null;
		IDfGroup objGroup = null;
		String groupName = null;
		try {
			LOGGER.debug("Enter into handleOnReturnFromProgressSuccess()");
			if (job.getService() instanceof ImportService) {
				ImportService importService = (ImportService) job.getService();
				List ids = importService.getNewObjectIds();
				// idfSession=
				// SessionManagerHttpBinding.getNewDfSessionManager().getSession(getCurrentDocbase());

				if (branch_number != null && cust_type != null) {
					groupName = "vb_" + branch_number.toLowerCase() + "_" + cust_type.toLowerCase() + "_group".toLowerCase();
				}

				IDfSession dfSession = getDfSession();

				IDfClient dfClient = DfClient.getLocalClient();

				IDfSessionManager sessionMgr = null;
				// ********************
				IDfLoginInfo loginInfo = null;
				IConfigLookup configLookup = ConfigService.getConfigLookup();
				Context ctx = getContext();

				//IConfigElement accInfo = configLookup.lookupElement("cs-install-owner-pwd", ctx);
				//LOGGER.debug("accInfo:" + accInfo);
				//accInfo.getValue();
				//LOGGER.debug("accinfo===" + accInfo.getValue());

				if (dfClient != null) {
					IDfLoginInfo li = new DfLoginInfo();
					LOGGER.debug("installation owner:" + dfSession.getServerConfig().getString("r_install_owner"));
					li.setUser(dfSession.getServerConfig().getString("r_install_owner"));

					//li.setPassword(accInfo.getValue());
					li.setPassword(lookupString("cs-install-owner-pwd"));
					li.setDomain(null);
					sessionMgr = dfClient.newSessionManager();
					sessionMgr.setIdentity(dfSession.getDocbaseName(), li);
				}

				if (sessionMgr != null)
					idfSession = sessionMgr.getSession(dfSession.getDocbaseName());

				for (int i = 0; i < ids.size(); i++) {
					if (idfSession != null) {

						if (groupName != null) {
							objGroup = (IDfGroup) idfSession.getObjectByQualification("dm_group where group_name = '" + groupName + "'");
							LOGGER.debug("Setting this group as imported object owner name:" + objGroup.getGroupName());
						}

						losObject = (IDfSysObject) idfSession.getObject(new DfId((String) ids.get(i)));
						//LOGGER.debug("Imported losObject:" + losObject);
						LOGGER.debug("object type:" + losObject.getTypeName());
						LOGGER.debug("Setting newly imported docuemnts properties:");

						losObject.setString("trans_id", sdddlTransactionId);
						// losObject.setString("object_name", get)
						if (object_name != null)
							losObject.setString("object_name", object_name);
						if (objGroup != null)
							losObject.setOwnerName(objGroup.getGroupName());
						if (doc_upload_status != null)
							losObject.setString("doc_upload_status", "Uploaded");

						if (doc_sub_type != null)
							losObject.setString("doc_sub_type", doc_sub_type);

						if (branch_number != null)
							losObject.setString("branch_number", branch_number);
						/*
						 * if(cust_email!=null)
						 * losObject.setString("cust_email",cust_email);
						 */
						if (cust_id_number != null)
							losObject.setString("cust_id_number", cust_id_number);

						if (cust_type != null)
							losObject.setString("cust_type", cust_type);

						if (cust_name != null)
							losObject.setString("cust_name", cust_name);

						if (rm_name != null)
							losObject.setString("rm_name", rm_name);

						if (collateral_id != null)
							losObject.setString("collateral_number", collateral_id);
						if (upload_by != null)
							losObject.setString("upload_by", upload_by);
						if (car_year_created != null)
							losObject.setString("car_year_created", car_year_created);
						if (upload_by != null)
							losObject.setString("upload_by", upload_by);

						// if(transaction_user!=null)
						// losObject.setString("transaction_user",transaction_user);

						if (cust_cif_number != null)
							losObject.setString("cust_cif_number", cust_cif_number);

						if (rm_id != null)
							losObject.setString("rm_id", rm_id);

						if (cust_id_type != null)
							losObject.setString("cust_id_type", cust_id_type);

						if (car_number != null)
							losObject.setString("car_number", car_number);

						if (doc_sub_type != null)
							losObject.setString("doc_sub_type", doc_sub_type);

						if (facility_number != null)
							losObject.setString("facility_number", facility_number);
						if (r_folder_path != null) {
							losObject.setString("subject", r_folder_path);
							LOGGER.debug("folder path======" + r_folder_path);
							losObject.link(r_folder_path);
						}
						// losObject.setString("", arg1)

						losObject.save();
						if (transactionObject != null) {
							transactionObject.setString("doc_upload_status", "Uploaded");
							transactionObject.save();
						}
					}
					// successMessage = checkConditions(rcsaObject);
					LOGGER.debug("handleOnReturnFromProgressSuccess() before leave");
					if (ids != null) {
						setReturnValue("newObjectIds", ids);

						LOGGER.debug("Object id:" + ids.get(i));
					}
				}

				addFinalSuccessMessage();
				super.handleOnReturnFromProgressSuccess(form, map, job);
			}
		} catch (Exception e) {
			throw new WrapperRuntimeException(e);
		}
	}

	@Override
	protected void handleOnReturnFromProgressRequestInput(Form form, Map map, JobAdapter job) {
		LOGGER.debug("handleOnReturnFromProgressRequestInput()");
		ArgumentList args = new ArgumentList();
		PromptEvent promptEvent = job.getPromptEvent();
		String strNotificationCode = getNoficationCode(promptEvent);
		String strNotificationMsg = getNoficationMsg(promptEvent);
		if (strNotificationCode.equals("XML_CA_I_SPECIFY_XML_APP")) {
			args.add("message", strNotificationCode + ": " + strNotificationMsg + "\n\n" + getString("MSG_SELECT_XML_APP_FROM_LIST"));
			String listValues[] = promptEvent.getListValues();
			String strValues = "";

			LOGGER.debug("list values:" + listValues.length);
			if (listValues != null) {
				StringBuffer buf = new StringBuffer(128);
				Util.buildAttrList(listValues, 0, listValues.length, buf);
				strValues = buf.toString();
				LOGGER.debug("strValues:" + strValues);
			}
			args.add("input", "dropdown");
			args.add("values", strValues);
			args.add("component", "promptinput");
			BackDetector.setComponentNested(this, "promptinputcontainer", null, args, getContext(), new FormActionReturnListener(this, "onReturnFromPromptInput"));
		} else if (strNotificationCode.equals("UCF_I_FILE_NOT_FOUND")) {
			args.add("fileName", strNotificationMsg);
			args.add("component", "locateimportlocalfile");
			BackDetector.setComponentNested(this, "locateimportlocalfilecontainer", null, args, getContext(), new FormActionReturnListener(this, "onReturnFromLocateFile"));
		} else {
			super.handleOnReturnFromProgressRequestInput(form, map, job);
		}
	}

	protected void addFinalSuccessMessage() {
		// setComponentPage("success");
		String s = getComponentPage();
		LOGGER.debug("addFinalSuccessMessage()" + s);
		LOGGER.debug("Sending eMail");
		try {
			String user = getDfSession().getLoginUserName();
			if (user != null) {
				IDfUser loginUser = (IDfUser) getDfSession().getObjectByQualification("dm_user where user_login_name='" + user + "'");
				String user_address = loginUser.getString("user_address");
				String Subject = "LOS document Uploaded successfully Transaction Id==" + sdddlTransactionId;
				String message = "Dear " + user + ",\n" + "This mail is to inform you about LOS document uploaded by you  " + " pertaining to transaction Id : "
						+ sdddlTransactionId

						+ "\n LOS document Request Details :\n" + "Object Name=" + losObject.getObjectName() + "\n" + "cif id= " + cust_cif_number + "\n" + "doc sub type= "
						+ doc_sub_type + "\n Custemer ID No= " + cust_id_number + "\n" + "Status= " + doc_upload_status + "\n" + "Uploaded By= " + upload_by + "\n"
						+ "CAR Year Created= " + car_year_created + "\n" + "\n" + " Automated email - Please do not reply as it's a system generated mail\n\n "

						+ "Thanks,\n"

						+ "ecmdmadmin@vietinbank.vn. \n";

				new SendMail();
				SendMail.sendMail(user_address, user, URL, Subject, message);

			}
		} catch (DfException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		MessageService.addMessage(this, "MSG_OPERATION_SUCCESSFUL");
	}

	@Override
	protected void invokeService(ContentTransferService service) {
		try {
			if (service instanceof ImportService) {

				ImportService importService = (ImportService) service;
				importService.setDestinationFolderId(getFolderId());
				// setComponentPage("success");
				LOGGER.debug("getFolderId()" + getFolderId());
				super.invokeService(service);
			} else {
				super.invokeService(service);
			}
		} catch (ContentTransferException e) {
			e.printStackTrace();
		}
	}

	protected Collection getFilesToImport() {
		return m_setFiles;
	}

	protected void setFilesToImport(Collection files) {
		Set f = ListOrderedSet.decorate(new HashSet());
		boolean mixed = false;
		if (files != null) {
			Object a[] = files.toArray();
			if (isFilesToImportSorted()) {
				Arrays.sort(a, getFilesToImportComparator());
			}
			ImportFile prev = null;
			for (int i = 0; i < a.length; i++) {
				f.add(a[i]);
				if (mixed) {
					continue;
				}
				ImportFile curr = (ImportFile) a[i];
				if (prev != null) {
					mixed = prev.isDirectory() != curr.isDirectory();
				}
				prev = curr;
			}

		}
		m_fileFolderMix = mixed;
		m_setFiles = f;
	}

	protected boolean isFilesToImportSorted() {
		return true;
	}

	protected Comparator getFilesToImportComparator() {
		return DIRS_FIRST;
	}

	private boolean isCurrenFileToImportDirectory() {
		int current = getCurrentComponent();
		ArgumentList args[] = getContainedComponentsArgs();
		return Boolean.valueOf(args[current].get("isDirectory")).booleanValue();
	}

	private boolean isPreviousFileToImportDirectory() {
		int current = getCurrentComponent();
		if (current > 0) {
			ArgumentList args[] = getContainedComponentsArgs();
			return Boolean.valueOf(args[current - 1].get("isDirectory")).booleanValue();
		} else {
			return false;
		}
	}

	protected String getFolderId() {
		return m_folderId;
	}

	protected void setFolderId(String folderId) {
		m_folderId = folderId;
	}

	protected void setTargetDocbaseName(String docbaseName) {
		m_targetDocbaseName = docbaseName;
	}

	protected String getTargetDocbaseName() {
		return m_targetDocbaseName;
	}

	protected Button getOkButtonControl(boolean create) {
		return (Button) getControl0("ok", create, com.documentum.web.form.control.Button.class);
	}

	protected Button getPreviousButtonControl(boolean create) {
		return (Button) getControl0("prev", create, com.documentum.web.form.control.Button.class);
	}

	protected FolderSelectionValidator getFolderValidatorControl(boolean create) {
		return (FolderSelectionValidator) getControl0("folderValidator", create, com.documentum.web.formext.control.validator.FolderSelectionValidator.class);
	}

	protected MultiDocbaseTree getFolderLocatorControl(boolean create) {
		return (MultiDocbaseTree) getControl0("folderlocator", create, com.documentum.web.formext.control.docbase.MultiDocbaseTree.class);
	}

	protected Panel getFolderFileIndicatorPanel(boolean create) {
		return (Panel) getControl0("folderFileIndicatorPanel", create, com.documentum.web.form.control.Panel.class);
	}

	protected Tabbar getFolderFileIndicatorTabbar(boolean create) {
		return (Tabbar) getControl0("folderFileIndicatorTabbar", create, com.documentum.web.form.control.Tabbar.class);
	}

	protected Tab getFolderIndicatorTab(boolean create) {
		return (Tab) getControl0("folderIndicatorTab", create, com.documentum.web.form.control.Tab.class);
	}

	protected Tab getFileIndicatorTab(boolean create) {
		return (Tab) getControl0("fileIndicatorTab", create, com.documentum.web.form.control.Tab.class);
	}

	Control getControl0(String name, boolean create, Class cl) {
		return create ? getControl(name, cl) : getControl(name);
	}

	public static List retrieveReturnObjectIds(Map onReturnMap) {
		List newObjectIdList = Collections.EMPTY_LIST;
		Object retNewIds = onReturnMap.get("newObjectIds");
		if (retNewIds != null && (retNewIds instanceof List)) {
			newObjectIdList = (List) retNewIds;
		} else {
			retNewIds = onReturnMap.get("newObjectIds");
			if (retNewIds != null && (retNewIds instanceof String[])) {
				String ids[] = (String[]) retNewIds;
				newObjectIdList = new ArrayList(ids.length);
				for (int i = 0; i < ids.length; i++) {
					newObjectIdList.add(ids[i]);
					LOGGER.debug("New Onject id" + ids[i]);
				}

			}
		}
		return newObjectIdList;
	}

	public void onSucess(Button button, ArgumentList args) {
		LOGGER.debug("onSucess");
		// setComponentReturn();
		// setComponentPage("success");
		setComponentJump("success", getContext());
		// setComponentJump("logout", getContext());

	}

	public void onCancel1(Control button, ArgumentList args)

	{
		LOGGER.debug("onCancel1");
		setComponentJump("success", getContext());

	}

}
